# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import logging
import pprint
import sys

from tornado import gen
from tornado.ioloop import IOLoop

from coin.base.config import Config
from coin.exchange.base.order_gateway import OrderSide, OrderType
from coin.exchange.binance.order_gateway import BinanceOrderGateway
from coin.exchange.binance.kr_rest.product import BinanceProduct
from coin.flow.simple_queue import SimpleQueue
import coin.flow.subscriber as flow_subscriber


class TestDriver(object):
  def __init__(self, ioloop):
    self._ioloop = ioloop
    self._og = BinanceOrderGateway([], [BinanceProduct.FromStr('BTC-USDT')],
                                   Config.from_config_filename('binance_pilot01'))
    queue = SimpleQueue('queue')
    self._og.start(queue, self._ioloop, flow_subscriber.from_queue(queue))
    self._ioloop.add_timeout(datetime.timedelta(seconds=5), self.print_balance)
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.loop)

  def print_balance(self):
    if self._og.is_ready():
      print('------------------------')
      print(datetime.datetime.now())
      print('BTC', self._og.get_balance('BTC'))
      print('USDT', self._og.get_balance('USDT'))
      pprint.pprint(self._og.get_working_order())
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.print_balance)

  @gen.coroutine
  def loop(self):
    self._og.cancel_all()
    yield gen.sleep(30)

    self._og.submit(BinanceProduct.FromStr('BTC-USDT'),
                    11000.,
                    0.002,
                    OrderSide.SELL,
                    OrderType.LIMIT)
    self._og.submit(BinanceProduct.FromStr('BTC-USDT'),
                    5000.,
                    0.002,
                    OrderSide.BUY,
                    OrderType.LIMIT)

    yield gen.sleep(20)
    self._og.cancel_all()


def main(argv):
  ioloop = IOLoop.current()
  TestDriver(ioloop)
  try:
    ioloop.start()
  except KeyboardInterrupt:
    pass


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  sys.exit(main(sys.argv))
